using System.Collections.Generic;
using LeetCodeQuestionBank.Models;
using Xunit;
using Newtonsoft.Json;

namespace LeetCodeQuestionBank.Algorithm
{
    public class No0061_RotateRight
    {
        /*
        给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。

        示例 1：
            输入：head = [1,2,3,4,5], k = 2
            输出：[4,5,1,2,3]
        示例 2：
            输入：head = [0,1,2], k = 4
            输出：[2,0,1]

        提示：
            链表中节点的数目在范围 [0, 500] 内
            -100 <= Node.val <= 100
            0 <= k <= 2 * 109
        */

        private const string LISTNODE_STR_INTERVAL = ",";

        public static IEnumerable<object[]> GetTestArgs()
        {
            return new object[][] {
                new object[] {
                    @"1,2,3,4,5", 2,
                    @"4,5,1,2,3",
                },
                new object[] {
                    @"0,1,2", 4,
                    @"2,0,1",
                },
            };
        }

        [Theory]
        [MemberData(nameof(GetTestArgs))]
        public void RotateRight_OnExecuteTest(string nodeStrInput, int k, string nodeStrResult)
        {
            var nodeInput = nodeStrInput.ToListNode(LISTNODE_STR_INTERVAL);
            var nodeResult = nodeStrResult.ToListNode(LISTNODE_STR_INTERVAL);
            Assert.Equal(nodeResult, RotateRight(nodeInput, k));
        }

        public ListNode RotateRight(ListNode head, int k)
        {
            if (k == 0 || head == null || head.next == null)
            {
                return head;
            }
            int n = 1;
            ListNode iter = head;
            while (iter.next != null)
            {
                iter = iter.next;
                n++;
            }
            int add = n - k % n;
            if (add == n)
            {
                return head;
            }
            iter.next = head;
            while (add-- > 0)
            {
                iter = iter.next;
            }
            ListNode ret = iter.next;
            iter.next = null;
            return ret;
        }
    }
}
